<?php
/**
 *退款模块
 * User: 梁晓伟  lxw11109@gmail.com
 * Date: 2017-09-16
 * Time: 9:47
 */

namespace App\Http\Controllers\Api\V1\Front\Mall;


use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Models\OrderDetail;
use App\Models\OrderRefund;
use App\Models\OrderRefundLog;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class RefundController extends Controller
{
    public function applyRefund(Request $request)
    {
        $data = $request->all();
        $validator = Validator::make($data,[
            'orderNo'        => 'required',
            'commodityList'   =>'required',
            'refundReason'  =>'required',
        ]);
        if($validator->fails()){
            return $this->apiResponse('', config('errorCode.INVALID_REQ_PARAMS'));
        }
        $commodityList = $data['commodityList'];
        $refund = [];
        $order = [];
       try{
            \DB::beginTransaction();
            foreach ($commodityList as $key=>$value){
                $refund[$key]['orderNo'] = $data['orderNo'];
                $refund[$key]['userId'] = $data['userId'];
                $user = User::find($data['userId']);
                $refund[$key]['userName'] = $user['nickName'];
                $orderDetail = OrderDetail::where(['orderNo'=>$data['orderNo'], 'skuId'=>$value['skuId']])->first();
                $abc = Order::where(['orderNo'=>$data['orderNo']])->first();
                if(!$orderDetail){
                    throw new \Exception("错误的参数");
                }
                $refund[$key]['refundPrice'] = $orderDetail['orderPrice'];
                $order['orderNo'] = $data['orderNo'];
                $order['skuId'] = $value['skuId'];

                //判断是否已经申请过了
                $status = OrderRefund::where($order)->first();
                if($status){
                    throw new \Exception("错误的参数");
                }

                $refund[$key]['refundStatus'] = 'PENDING';
                $refund[$key]['refundReason'] = $data['refundReason'];
                $refund[$key]['applyTime'] = date("Y-m-d H:i:s", time());
                $refund[$key]['descPictures'] = $data['descPictures'];
                $refund[$key]['commodityId'] = $value['commodityId'];
                $refund[$key]['orderDetailId'] = $orderDetail['detailId'];
                $refund[$key]['payType'] = $abc['payType'];
                $refund[$key]['skuId'] = $value['skuId'];
                $refund[$key]['refundNo'] = getOrderSn("T");
            }
            $refundTotal = OrderRefund::where('orderNo',$data['orderNo'])->count();//计算已经申请过几个退款商品
            $orderTotal = OrderDetail::where('orderNo',$data['orderNo'])->count();//计算购买的商品总数（只计算单个的）
            $applyTotal = count($commodityList);
            if(($refundTotal + $applyTotal) === $orderTotal){//证明商品已经全部退款，需要 改变订单状态
                $status = Order::where('orderNo',$data['orderNo'])->update(['orderStatus'=>'WAITREFUND']);
                if(!$status){
                    throw new \Exception("修改订单状态失败");
                }
            }
            $status = OrderRefund::insert($refund);
            $bc = OrderRefund::where('orderNo',$data['orderNo'])->get()->toArray();
            foreach ($bc as $k=>$v){
                $abc = [];
                $abc['refundId'] = $v['refundId'];
                $abc['content'] = '已申请退款';
                $abc['createTime'] = date('Y-m-d H:i:s');
                OrderRefundLog::create($abc);
            }

            if(!$status){
                throw new \Exception("插入退款数据失败");
            }
            \DB::commit();
            return $this->apiResponse(true);

        }catch (\Exception $e){
            \DB::rollback();
            \Log::error("RefundController applyRefund ".$e->getMessage());
            return $this->apiResponse('', config('errorCode.INVALID_REQ_PARAMS'));
        }

    }

    /**
     * 撤销退款请求
     * @param Request $request
     * @param $refundId
     * @return \Illuminate\Http\JsonResponse
     */
    public function cancelRefund(Request $request, $refundId)
    {
        try{
            \DB::beginTransaction();
            $status = OrderRefund::where(['refundId'=>$refundId])->whereNotIn('refundStatus',array('FAILED','SUCCEEDED','REVOKED'))->update(['refundStatus'=>'REVOKED']);
            $orderNo = OrderRefund::where(['refundId'=>$refundId])->first();
            $refundTotal = OrderRefund::where(['orderNo'=>$orderNo['orderNo']])->whereIn('refundStatus',array('FAILED','SUCCEEDED','REVOKED'))->count();
            $orderTotal = OrderDetail::where(['orderNo'=>$orderNo['orderNo']])->count();
            if($refundTotal === $orderTotal){//证明得改吧订单状态
                 $order = Order::where(['orderNo'=>$orderNo['orderNo']])->first();
                 if($order['deliverNo']){
                     $status = Order::where(['orderNo'=>$orderNo['orderNo']])->update(['orderStatus'=>'WAITRECEIVE']);
                 }else{
                     $status = Order::where(['orderNo'=>$orderNo['orderNo']])->update(['orderStatus'=>'WAITDELIVER']);
                 }
                 if(!$status){
                     throw new \Exception("更新订单状态失败");
                 }
            }
            \DB::commit();
            return $this->apiResponse('','取消成功');
        }catch (\Exception $e){
            \DB::rollback();
            \Log::error("RefundController cancelRefund ".$e->getMessage());
            return $this->apiResponse('', config('errorCode.INVALID_REQ_PARAMS'));
        }
    }

    public function updateDeliver(Request $request)
    {
        $data = $request->all();
        if(!$data){
            return $this->apiResponse('', config('errorCode.INVALID_REQ_PARAMS'));
        }
        try{

            \DB::beginTransaction();

              $status = OrderRefund::where('refundId',$data['refundId'])->update(['deliverName'=>$data['deliverName'],'refundStatus'=>"WAITCONFIRM",'deliverNo'=>$data['deliverNo'],'deliverCode'=>$data['deliverCode']]);
              if(!$status){
                    throw new \Exception("更新退款订单失败");
              }
            $abc = [];
            $abc['refundId'] = $data['refundId'];
            $abc['content'] = '等待卖家确认收货';
            $abc['createTime'] = date('Y-m-d H:i:s');
            OrderRefundLog::create($abc);
            \DB::commit();
            return $this->apiResponse(true);
        }catch (\Exception $e){
            \DB::rollback();
            \Log::error("RefundController updateDeliver ".$e->getMessage());
            return $this->apiResponse('', config('errorCode.INVALID_REQ_PARAMS'));
        }

    }
}